package net.dgg.dggcloud.service.jrcrm.service.orf.api;

import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerRecordConstant;
import net.dgg.dggcloud.service.jrcrm.constant.OrderConstant;
import net.dgg.dggcloud.service.jrcrm.entity.customer.ReturnVisitCustomer;
import net.dgg.dggcloud.service.jrcrm.entity.orf.Order;
import net.dgg.dggcloud.service.jrcrm.entity.orf.OrderBusiness;
import net.dgg.dggcloud.service.jrcrm.service.business.BusinessAbilityService;
import net.dgg.dggcloud.service.jrcrm.service.customer.ReturnVisitCustomerService;
import net.dgg.dggcloud.service.jrcrm.service.orf.OrderBusinessService;
import net.dgg.dggcloud.service.jrcrm.service.orf.OrderService;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xianlincai
 * 订单接口service
 * @create 2017-11-29 9:27
 **/
@Service
public class OrderApiService  extends BaseService{

    @Resource
    private OrderBusinessService  orderBusinessService;//子订单

    @Resource
    private OrderService orderService;//主订单

    @Resource
    private BusinessAbilityService businessAbilityService;//商机

    @Resource
    private ReturnVisitCustomerService returnVisitCustomerService;//回访记录

    /**
     *  订单状态同步
     * @param datas 参入参数</br>
     *    mainOrderId :销售主订单id</br>
     *    childOrderId :销售子订单id</br>
     *    currentUser :当前用户</br>
     *    orderStatus :状态</br>
     *                ORF_BDZT_2 :退单
     *                ORF_BDZT_1:成单
     *                ORF_BDZT_5:生产中
     *                ORF_BDZT_4:暂缓
     *                ORF_BDZT_3:废单
     *
     * @return 返回信息 </br>
     *         status :0成功1失败
     *         message:成功失败信息
     */
    public Map<String,String>  synOrderState(Map<String,Object> datas){
        try{
            if(datas!=null){
                Object mainOrderId = datas.get("mainOrderId");//主订单id
                Object childOrderId = datas.get("childOrderId");//子订单id
                Object orderStatus = datas.get("orderStatus");//状态
                Object currentUser = datas.get("currentUser");//当前用户
                if(mainOrderId==null ){
                    return getResult(OrderConstant.ERROR_STATUS,"主订单id为空！");
                }
                if(childOrderId==null ){
                    return  getResult(OrderConstant.ERROR_STATUS,"子订单id为空！");
                }
                if(orderStatus==null){
                    return  getResult(OrderConstant.ERROR_STATUS,"更新状态不存在！");
                }
                if(currentUser==null){
                    return  getResult(OrderConstant.ERROR_STATUS,"当前用户不存在！");
                }
                User user= (User) currentUser;
                if(user.getId()==null){
                    return  getResult(OrderConstant.ERROR_STATUS,"当前用户id不存在！");
                }
                if(user.getOrgId()==null){
                    return   getResult(OrderConstant.ERROR_STATUS,"当前用户组织不存在！");
                }
                 updateOrders(mainOrderId, childOrderId, orderStatus,user);
            }else{
                return  getResult(OrderConstant.ERROR_STATUS,"参入参数为空！");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("生产订单同步销售订单异常！"+e.getMessage());
            return  getResult(OrderConstant.ERROR_STATUS,"生产订单同步销售订单异常！"+e.getMessage());
        }
        return getResult(OrderConstant.SUCCESS_STATUS,"更新成功");
    }

    /**
     * 更新订单相关西你想
     * @param mainOrderId:主订单
     * @param childOrderId：子订单
     * @param orderStatus:订单状态
     * @return
     */
    @Transactional
    protected void updateOrders(Object mainOrderId, Object childOrderId, Object orderStatus,User user) {
        //更新
        List<OrderBusiness> orderBusinesses = orderBusinessService.queryOrder("id", Long.parseLong(childOrderId.toString()));//子订单
        if(!orderBusinesses.isEmpty()){
            OrderBusiness orderBusiness = orderBusinesses.get(0);
            orderBusiness.setStatus(orderStatus.toString());
            orderBusiness.setUpdaterUser(user);
            orderBusinessService.updateOrderBusiness(orderBusiness);
        }else{
            throw new BizException(childOrderId+"信息没有找到！",10006);
        }
        Order order = orderService.getByIdHiber(Long.parseLong(mainOrderId.toString()));
        String newOrderStatus=orderStatus.toString();
        if(order!=null){
             if(newOrderStatus.equals(OrderConstant.ORF_BDZT_1) || newOrderStatus.equals(OrderConstant.ORF_BDZT_2) || newOrderStatus.equals(OrderConstant.ORF_BDZT_3)){
                 //成单或者退单
                 if(newOrderStatus.equals(OrderConstant.ORF_BDZT_3) || newOrderStatus.equals(OrderConstant.ORF_BDZT_2)){
                     newOrderStatus=OrderConstant.ORF_DDZT_3;//如果是退单、废单主订单就是退单
                 }else if(newOrderStatus.equals(OrderConstant.ORF_BDZT_1)){
                     newOrderStatus=OrderConstant.ORF_DDZT_6;//如果是成单主订单就是成单
                 }
                 order.setStatus(newOrderStatus);
                 order.setUpdaterUser(user);
                 orderService.updateOrder(order);
                 //20181106成单退单不修改商机状态
                 //updateBusState(order,user,newOrderStatus);
             }
        }else{
            throw new BizException(mainOrderId+"信息没有找到！",10006);
        }
    }

    /**
     *
     *获取返回结果map </br>
     * @param status   状态 1:失败 0：成功 </br>
     * @param message  消息 </br>
     * @return
     */
    private Map<String,String> getResult(String status,String message){
        Map<String,String> results=new HashedMap();//结果信息
        results.put("status",status);//状态
        results.put("message",message);//消息
        return results;
    }


    /**
     * 调用商机接口状态修改
     * @param order
     * @param user
     * @param status
     */
    @Transactional
    protected void updateBusState(Order order,User user,String status){
        try{
            if(OrderConstant.ORF_DDZT_6.equals(status)){
                //成单
                businessAbilityService.updateBusinessOrderInfo(order,user.getId(), CustomerRecordConstant.BUS_OPERATE_ORDER_SUCCESS);
            }
            //退单
            if(OrderConstant.ORF_DDZT_3.equals(status)){
                businessAbilityService.updateBusinessOrderInfo(order,user.getId(), CustomerRecordConstant.BUS_OPERATE_BACKORDER);
            }
            Map map = new HashMap();
//            map.put("queryType","NO"); //未回访已回访是否有记录
            map.put("customerId",order.getCustomerId());
            Integer i = returnVisitCustomerService.getCountReturnVisitCustomerList(map);
            ReturnVisitCustomer rvc = new ReturnVisitCustomer();
            if(i<1) {
                //调用回访记录
                rvc.setCreateUser(user);
                rvc.setUpdaterUser(user);
                rvc.setCustomerId(order.getCustomerId());
                rvc.setLastBusId(order.getBusinessId());
                returnVisitCustomerService.saveOrUpdateReturnVisitCustomer(rvc);
            }
        }catch (Exception e){
            throw new BizException("接口信息同步失败！"+e.getMessage(),10006);

        }

    }
}
